from __future__ import absolute_import
import os
import os.path
import glob
import logging
import pwd
import grp

from os.path import isdir #, join
from forest.registry import register_tool
from forest.tool import Tool

logger = logging.getLogger('forest.tools.system.chmod')

def joinpaths(*args, **kwargs):
    path = os.path.sep.join(args)

    if kwargs.get("follow_symlinks"):
        return os.path.realpath(path)
    else:
        return path

@register_tool('system.chown')
def chown(path, user=None, group=None, recursive=False):
    Tool.SIGNAL_TOOL_START(chown, level=logging.DEBUG, message='Chown: %s %s %s recursive: %s' % (path, user, group, recursive))

    uid = gid = -1

    if user is not None:
        uid = pwd.getpwnam(user)[2]

    if group is not None:
        gid = grp.getgrnam(group)[2]

    for fname in glob.iglob(path):
        os.chown(fname, uid, gid)

        if recursive and isdir(fname):
            for nested in os.listdir(fname):
                nested = joinpaths(fname, nested)
                chown(nested, user, group, recursive)
